import { connectWS } from "@/api/chat";
import { wsSend } from "../utils";
export class SmartMeeting {
  constructor(url, meetingId) {
    this.url = url;
    this.open = false;
    this.wsTask = {};
    this.meetingId = meetingId; //小会场id
    this.memberId = ""; //用户id
    this.timeout = 4000; //心跳信息响应时间
    this.interval = 8000; //发心跳间隔时间
    this.clientTimer = null;
    this.severTimer = null;
    this.reconnectNum = 0;
    this.reconnectLimit = 5;
    this.unconnect = false;
  }
  createWs() {
    this.wsTask = connectWS(this.url);
    this.wsListenter();
  }

  wsListenter() {
    this.wsTask.addEventListener("open", () => {
      this.open = true;
      // this.heartStart()
    });
    this.wsTask.addEventListener("message", () => {
      // this.heartStart()
    });
    this.wsTask.addEventListener("close", () => {
      this.open = false;
    });
  }
  heartStart() {
    this.serverTimer && clearTimeout(this.serverTimer);
    this.clientTimer && clearInterval(this.clientTimer);
    this.clientTimer = setInterval(() => {
      //发送消息，服务端返回信息，即表示连接良好，可以在socket的onmessage事件重置心跳机制函数
      const params = {
        type: "0x25",
        content: "小会场心跳"
      };
      wsSend(this.wsTask, params);
      //定义一个延时器等待服务器响应，若超时，则关闭连接，重新请求server建立socket连接
      this.serverTimer = setTimeout(() => {
        this.wsTask.close();
        this.reConnect();
        this.serverTimer && clearTimeout(this.serverTimer);
      }, this.timeout);
    }, this.interval);
  }
  reConnect() {
    if (this.reconnectNum >= this.reconnectLimit) {
      this.serverTimer && clearTimeout(this.serverTimer);
      this.clientTimer && clearInterval(this.clientTimer);
      this.reconnectNum = 0;
      this.unconnect = true;
      return;
    }
    this.reconnectNum++;
    this.createWs()
  }
}
